<?php

use addons\epay\library\Service;
use fast\Http;
use think\Env;
use think\Log;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;

function getAppIdAndSecret()
{
    # 小程序
    $appid = Env::get('wechat.mini_appid');
    $app_secret = Env::get('wechat.mini_secret');
    # 公众号
    $appidgz = "";
    $app_secretgz = "";
    return array($appid, $app_secret, $appidgz, $app_secretgz);
}


#  微信退款
function refundOrder($order_no, $money)
{
    $config = Service::getConfig('wechat');
    $refund_order = [
        'out_trade_no' => $order_no ?? '',
        'total_fee' => $money * 100 ?? 0,
        'refund_fee' => $money * 100 ?? 0,
        'out_refund_no' => time(),
        'refund_desc' => '订单退款'
    ];
    $pay = \Yansongda\Pay\Pay::wechat($config)->refund($refund_order);
    return $pay;
}

# 获取微信access_token
function getAccessToken()
{
    list($appid, $app_secret) = getAppIdAndSecret();
    $api = "https://api.weixin.qq.com/cgi-bin/stable_token";
    $result = json_decode(Http::post($api, json_encode([
        'grant_type' => 'client_credential',
        'appid' => $appid,
        'secret' => $app_secret
    ])), true);
    if (!isset($result['access_token']) || !$result['access_token']) {
        throw new \think\Exception($result['errmsg']);
    }
    return $result['access_token'];
}

/**
 * @title 获取手机号
 * @param string $wechatCode
 * @return mixed
 * @throws \think\Exception
 */
function getWxPhone(string $wechatCode)
{
    throw_validate_error(!$wechatCode, "缺少微信手机号code错误");
    $access_token = getAccessToken();
    $api = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$access_token";
    $data = [
        'code' => $wechatCode
    ];
    $result = Http::sendRequest($api, json_encode($data));
    $response = json_decode($result['msg'], true);
    throw_validate_error($response['errcode'] != 0, $response['errmsg']);
    throw_validate_error(!$response['phone_info']['purePhoneNumber'], "获取手机号码为空");
    return $response['phone_info']['purePhoneNumber'];
}

# 获取微信 openid
function getOpenId($wechatCode)
{
    list($appid, $appSecret) = getAppIdAndSecret();
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $appSecret . "&js_code=" . $wechatCode . "&grant_type=authorization_code";
    $access_token = json_decode(Http::get($url), true);

    Log::info("code置换结果" . json_encode($access_token));
    throw_validate_error(isset($access_token['errcode']), "code置换失败");
    return $access_token;
}

